/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-JDInterface
*
* @File name : JDInterfaceService.java
*
* @Author : Administrator
*
* @Date : 2017年4月11日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年4月11日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.JDInterface.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.FrameHttpUtil;
import org.marketing.common.dms.dto.SendMessage;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventShoppingJDDTO;
import org.marketing.common.event.EventShoppingSendWeixinDto;
import org.marketing.common.event.EventShoppingToPayDTO;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.MD5Util;
import org.marketing.common.util.MapConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.common.service.BaseService.MQChannelType;
import com.yonyou.gmmc.service.JDInterface.constant.JDInterfaceConstant;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpOrderInfoMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpOrderProductInfoMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpShoppingCarMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TpAccessTokenMapper;
import com.yonyou.gmmc.service.JDInterface.model.TmTpOrderInfo;
import com.yonyou.gmmc.service.JDInterface.model.TmTpOrderProductInfo;
import com.yonyou.gmmc.service.JDInterface.model.TmTpShoppingCar;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpAddressMapper;
import com.yonyou.gmmc.service.JDInterface.dao.TmTpBalanceDetailMapper;
import com.yonyou.gmmc.service.JDInterface.model.OrderDto;
import com.yonyou.gmmc.service.JDInterface.model.TmTpAddress;
import com.yonyou.gmmc.service.JDInterface.model.TmTpBalanceDetail;
import com.yonyou.gmmc.service.JDInterface.model.TpAccessToken;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import tk.mybatis.mapper.entity.Example;

/**
 * @author Administrator TODO description
 * @date 2017年4月11日
 */
@Transactional
@Service("JDInterfaceService")
public class JDInterfaceService {

    private Logger                     logger                = Logger.getLogger(JDInterfaceService.class);
    private static String              checkAreaLimitUrl     = "https://bizapi.jd.com/api/product/checkAreaLimit";
    private static String              newStockByIdUrl       = "https://bizapi.jd.com/api/stock/getNewStockById";
    private static String              stockByIdUrl          = "https://bizapi.jd.com/api/stock/getStockById";
    private static String              getBalanceUrl         = "https://bizapi.jd.com/api/price/getBalance";
    private static String              getBalanceDetailUrl   = "https://bizapi.jd.com/api/price/getBalanceDetail";
    private static String              selectJincaiCreditUrl = "https://bizapi.jd.com/api/price/selectJincaiCredit";
    @Autowired
    private TpAccessTokenMapper        tpAccessTokenMapper;

    @Autowired
    private TmTpAddressMapper          tmTpAddressMapper;

    @Autowired
    private TmTpOrderInfoMapper        tmTpOrderInfoMapper;

    @Autowired
    private TmTpOrderProductInfoMapper tmTpOrderProductInfoMapper;

    @Autowired
    private TmTpShoppingCarMapper      tmTpShoppingCarMapper;

    @Autowired
    private TmTpBalanceDetailMapper    tmTpBalanceDetailMapper;

    @Autowired
    private BaseService                eventService;

    @Value("${ifPay}")
    private String                     ifPay;

    @Value("${TOKEN_USERNAME}")
    private String                     TOKEN_USERNAME;
    @Value("${TOKEN_PASSWORD}")
    private String                     TOKEN_PASSWORD;
    @Value("${TOKEN_USERNAME_ENCODEURI}")
    private String                     TOKEN_USERNAME_ENCODEURI;
    @Value("${TOKEN_PASSWORD_MD5}")
    private String                     TOKEN_PASSWORD_MD5;
    @Value("${TOKEN_SCOPE}")
    private String                     TOKEN_SCOPE;
    @Value("${TOKEN_CLIENT_ID}")
    private String                     TOKEN_CLIENT_ID;
    @Value("${TOKEN_CLIENT_SECRET}")
    private String                     TOKEN_CLIENT_SECRET;
    @Value("${TOKEN_GRANT_TYPE}")
    private String                     TOKEN_GRANT_TYPE;

    /**
     * 获取京东TOKEN
     * 
     * @author Administrator
     * @date 2017年4月12日
     * @return
     * @throws Exception
     */
    public String getToken() throws Exception {
        String tokens = "";
        tokens = tpAccessTokenMapper.selectToken();
        if (tokens == null) {
            logger.info("Token为空");
            String grant_type = TOKEN_GRANT_TYPE;
            String client_id = TOKEN_CLIENT_ID;
            String client_secret = TOKEN_CLIENT_SECRET;
            String username = TOKEN_USERNAME_ENCODEURI;
            String password = TOKEN_PASSWORD_MD5;
            Date date = new Date();
            SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String timestamp = sdformat.format(date);
            String url = "https://bizapi.jd.com/oauth2/accessToken";
            String sign = client_secret + timestamp + client_id + TOKEN_USERNAME + password + grant_type
                          + client_secret;
            sign = MD5Util.MD5(sign).toUpperCase();
            String param = "grant_type=access_token" + "&client_id=" + client_id + "&username=" + username
                           + "&password=" + password + "&timestamp=" + timestamp + "&sign=" + sign;
            String str = FrameHttpUtil.sendPost(url, param);
            logger.info("返回结果" + str);
            // 将TOKEN保存进数据库
            JSONObject jsonObject1 = JSONObject.fromObject(str);
            if (jsonObject1 == null || jsonObject1.isNullObject()) {
                logger.info("返回结果为空");
            } else {

                String result = jsonObject1.getString("result");
                logger.info("result>>---------------" + result);
                JSONObject jsonObject2 = JSONObject.fromObject(result);
                if (jsonObject2 == null || jsonObject2.isNullObject()) {
                    logger.info("返回结果为空");
                } else {
                    TpAccessToken token = new TpAccessToken();
                    token.setTokenId((long) 1);
                    token.setAccessToken(jsonObject2.getString("access_token"));
                    token.setUids(jsonObject2.getString("uid"));

                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Long refresh_token_expires = new Long(jsonObject2.getString("refresh_token_expires"));
                    String d = format.format(refresh_token_expires);
                    token.setRefreshTokenExpires(format.parse(d));

                    Long time = new Long(jsonObject2.getString("time"));
                    String ds = format.format(time);
                    token.setTimes(format.parse(ds));

                    token.setExpiresIn(Long.valueOf(jsonObject2.getString("expires_in")));
                    token.setRefreshToken(jsonObject2.getString("refresh_token"));
                    // 查询TOKEN表里是否有值
                    List<TpAccessToken> l = tpAccessTokenMapper.selectAll();
                    if (l == null || l.size() == 0) {
                        // 没有值，新增一条token
                        logger.info("新增一个TOKEN");
                        token.setCreateDate(new Date());
                        tpAccessTokenMapper.insertToken(token);
                    } else {
                        // 有值，更新token
                        logger.info("更新TOKEN");
                        token.setUpdateDate(new Date());
                        tpAccessTokenMapper.updateToken(token);
                    }
                    tokens = token.getAccessToken();
                }
            }
        } 
        return tokens;
    }

    /**
     * 更新TOKEN
     * 
     * @author Administrator TODO description
     * @date 2017年4月12日
     * @return
     * @throws Exception
     */
    public String refreshToken() throws Exception {
        String access_token = "";
        // 查询TOKEN表
        List<TpAccessToken> l = tpAccessTokenMapper.selectAll();
        if (l == null || l.size() == 0) {
            // 表中没有值
            access_token = getToken();
        } else {
            // 有数据，拿到refresh_token
            String refresh_token = l.get(0).getRefreshToken();
            String client_id = TOKEN_CLIENT_ID;
            String client_secret = TOKEN_CLIENT_SECRET;
            String url = "https://bizapi.jd.com/oauth2/refreshToken";
            String param = "refresh_token=" + refresh_token + "&client_id=" + client_id + "&client_secret="
                           + client_secret;
            // 调用京东接口刷新TOKEN
            String str = FrameHttpUtil.sendPost(url, param);

            // 将TOKEN保存进数据库
            JSONObject jsonObject1 = JSONObject.fromObject(str);
            if (jsonObject1 == null || jsonObject1.isNullObject()) {
            } else {

                String resultCode = jsonObject1.getString("resultCode");
                if (resultCode.equals("0000")) {
                    String result = jsonObject1.getString("result");
                    JSONObject jsonObject2 = JSONObject.fromObject(result);

                    TpAccessToken token = new TpAccessToken();
                    token.setTokenId((long) 1);
                    token.setAccessToken(jsonObject2.getString("access_token"));
                    token.setUids(jsonObject2.getString("uid"));

                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Long refresh_token_expires = new Long(jsonObject2.getString("refresh_token_expires"));
                    String d = format.format(refresh_token_expires);
                    token.setRefreshTokenExpires(format.parse(d));

                    Long time = new Long(jsonObject2.getString("time"));
                    String ds = format.format(time);
                    token.setTimes(format.parse(ds));

                    token.setExpiresIn(Long.valueOf(jsonObject2.getString("expires_in")));
                    token.setRefreshToken(jsonObject2.getString("refresh_token"));

                    logger.info("更新TOKEN");
                    token.setUpdateDate(new Date());
                    tpAccessTokenMapper.updateToken(token);

                    access_token = token.getAccessToken();
                } else {
                    // 调用错误
                    access_token = jsonObject1.getString("resultMessage");
                }
            }
        }
        return access_token;
    }

    /**
     * 7.1 统一下单接口
     * 
     * @author Administrator TODO description
     * @date 2017年4月17日
     * @return
     * @throws Exception
     */
    public Map<String, Object> submitOrder(Map<String, Object> queryMap) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String userType = "";
        String thirdOrder = queryMap.get("thirdOrder").toString();
        String userId = queryMap.get("userId").toString();
        String openId = "";
        String deductPoints = "";
        String phone = "";
        BizEvent event = new BizEvent();
        try {
            if (userId == null) {
                // 非车主
                logger.info("不是车主！");
            } else {
                // 将车主ID保存
                logger.info("车主ID——" + userId);
                // 查TOKEN
                String token = tpAccessTokenMapper.selectToken();
                logger.info("TOKEN——" + token);
                if (token == null || token == "") {
                    // 没有获取到TOKEN
                    resultMap.put("errorCode", JDInterfaceConstant.RESULTCODE_2007);
                    resultMap.put("resultMsg", "没有获取到TOKEN");
                } else {
                    // 查询订单详情
                    TmTpOrderInfo orderDto = new TmTpOrderInfo();
                    orderDto.setThirdOrder(thirdOrder);
                    orderDto = tmTpOrderInfoMapper.selectOne(orderDto);
                    logger.info("订单详情——" + orderDto);
                    if (orderDto == null) {
                        // 不存在该订单
                        resultMap.put("errorCode", JDInterfaceConstant.RESULTCODE_3401);
                        resultMap.put("resultMsg", "没有该订单");
                    } else {
                        // 查询订单商品详情
                        List<TmTpOrderProductInfo> orderProductDto = tmTpOrderProductInfoMapper.selectProductInfo(thirdOrder);
                        if (orderProductDto == null || orderProductDto.size() == 0) {
                            // 该订单中无商品信息
                            resultMap.put("errorCode", JDInterfaceConstant.RESULTCODE_3005);
                            resultMap.put("resultMsg", "订单中没有商品信息");
                        } else {
                            // 将商品信息转化JSON
                            String sku = JSON.toJSON(orderProductDto).toString();
                            logger.info("订单商品详情——" + sku);
                            // 查询价格快照
                            List<TmTpOrderProductInfo> orderPriceDto = tmTpOrderProductInfoMapper.selectPriceSnap(thirdOrder);
                            String orderPriceSnap = JSON.toJSON(orderPriceDto).toString();
                            logger.info("订单商品快照——" + orderPriceSnap);
                            String url = "https://bizapi.jd.com/api/order/submitOrder";
                            // 拼参数
                            String params = "token=" + token + "&thirdOrder=" + orderDto.getThirdOrder() + "&sku=" + sku
                                            + "&name=" + orderDto.getName() + "&province=" + orderDto.getProvince()
                                            + "&city=" + orderDto.getCity() + "&county=" + orderDto.getCounty()
                                            + "&town=" + orderDto.getTown() + "&address=" + orderDto.getAddress()
                                            + "&mobile=" + orderDto.getMobile() + "&email=" + orderDto.getEmail() 
                                            + "&remark=" + orderDto.getRemark() + "&invoiceState=" + orderDto.getInvoiceState() 
                                            + "&invoiceType=" + orderDto.getInvoiceType() + "&selectedInvoiceTitle="
                                            + orderDto.getSelectedInvoiceTitle() + "&companyName="
                                            + orderDto.getCompanyName() + "&invoiceContent="
                                            + orderDto.getInvoiceContent() + "&paymentType=" + orderDto.getPaymentType()
                                            + "&isUseBalance=" + orderDto.getIsUseBalance() + "&submitState="
                                            + orderDto.getSubmitState() + "&doOrderPriceMode="
                                            + orderDto.getDoOrderPriceMode() + "&orderPriceSnap=" + orderPriceSnap;

                            // 下单到京东
                            String result = FrameHttpUtil.sendPost(url, params);
                            logger.info("京东返回结果——" + result);
                            // 拿到返回信息中的SUCCESS
                            JSONObject jsonObject1 = JSONObject.fromObject(result);
                            String success = jsonObject1.getString("success");
                            if (success.equals("false")) {
                                // 下单失败
                                // 拿到错误信息中的返回码
                                JSONObject jsonObject2 = JSONObject.fromObject(result);
                                String resultCode = jsonObject2.getString("resultCode");
                                if (resultCode.equals("0008")) {
                                    // 重复下单
                                    resultMap.put("errorCode", resultCode);
                                    resultMap.put("resultMsg", "重复下单");
                                } else {
                                    // 其他错误
                                    JSONObject jsonObject3 = JSONObject.fromObject(result);
                                    String resultMessage = jsonObject3.getString("resultMessage");
                                    resultMap.put("errorCode", resultCode);
                                    resultMap.put("resultMsg", resultMessage);
                                }
                            } else {
                                // 下单成功
                                resultMap.put("errorCode", JDInterfaceConstant.RESULTCODE_0001);
                                resultMap.put("resultMsg", "下单成功");
                                // 更新订单信息
                                JSONObject jsonObject4 = JSONObject.fromObject(result);
                                String resultMessage = jsonObject4.getString("result");
                                JSONObject jsonObject5 = JSONObject.fromObject(resultMessage);
                                String jdOrderId = jsonObject5.getString("jdOrderId");
                                String freight = jsonObject5.getString("freight");
                                String orderPrice = jsonObject5.getString("orderPrice");
                                String orderNakedPrice = jsonObject5.getString("orderNakedPrice");
                                String orderTaxPrice = jsonObject5.getString("orderTaxPrice");
                                String skus = jsonObject5.getString("sku");
                                TmTpOrderInfo orderInfoDto = new TmTpOrderInfo();
                                orderInfoDto.setJdOrderId(jdOrderId);
                                logger.info("京东单号——" + orderInfoDto.getJdOrderId());
                                orderInfoDto.setFreight(freight);
                                logger.info("总运费——" + orderInfoDto.getFreight());
                                orderInfoDto.setOrderPrice(orderPrice);
                                logger.info("商品总价格——" + orderInfoDto.getOrderPrice());
                                orderInfoDto.setOrderNakedPrice(orderNakedPrice);
                                logger.info("订单裸价——" + orderInfoDto.getOrderNakedPrice());
                                orderInfoDto.setOrderTaxPrice(orderTaxPrice);
                                logger.info("订单税额——" + orderInfoDto.getOrderTaxPrice());
                                orderInfoDto.setSku(skus);
                                logger.info("商品信息——" + orderInfoDto.getSku());
                                orderInfoDto.setUpdateDate(new Date());
                                Example example = new Example(TmTpOrderInfo.class);
                                example.createCriteria().andCondition("THIRD_ORDER=", thirdOrder);
                                int i = tmTpOrderInfoMapper.updateByExampleSelective(orderInfoDto, example);
                                logger.info("更新了——" + i);
                                // 在购物车中删除该订单里的所有商品信息
                                Example ex = new Example(TmTpShoppingCar.class);
                                ex.createCriteria().andCondition("USER_ID=", userId);
                                int s = tmTpShoppingCarMapper.deleteByExample(ex);
                                logger.info("购物车删除了——" + s);
                                // 生成京东订单，开始扣分
                                String x = "";
                                logger.info("获取用户类型");
                                userType = queryMap.get("userType").toString();
                                if (userType.equals("1")) {
                                    logger.info("用户类型为微信用户——开始扣分");
                                    deductPoints = queryMap.get("PointsNum").toString();
                                    phone = queryMap.get("phone").toString();
                                    EventShoppingToPayDTO orderEventDto = new EventShoppingToPayDTO();
                                    orderEventDto.setPhone(phone);
//                                    logger.info("下单的手机号——" + orderEventDto.getPhone());
                                    orderEventDto.setPointsNum(Long.valueOf(deductPoints));
//                                    logger.info("订单需要扣减的金额——" + orderEventDto.getPointsNum());
                                    orderEventDto.setShoppingOrderNo(thirdOrder);
//                                    logger.info("订单号——" + orderEventDto.getShoppingOrderNo());
                                    orderEventDto.setUserId(Integer.valueOf(userId));
//                                    logger.info("下单的用户id——" + orderEventDto.getUserId());
                                    event.setEventBizType(EventBizType.SHOPPIING_ORDER);
                                    event.setEventBizStep(EventBizStep.SHOPPIING_ORDER_JD);
                                    event.setEventKey(orderEventDto.getShoppingOrderNo());
                                    event.setEventData(MapConverUtil.PO2Map(orderEventDto));
                                    x = eventService.sendEvent2MQ(event);
                                    logger.info("扣分MQ返回结果>>>>>>>>>>>>>>>>>>>>" + x);
                                } else if (userType.equals("2")) {
                                    logger.info("用户类型为销售顾问");
                                    openId = queryMap.get("openId").toString();
                                    deductPoints = queryMap.get("deductPoints").toString();
                                    x = shoppingSendMq(openId, Long.valueOf(deductPoints));
                                    logger.info("MQ返回信息>>>>" + x);
                                } else {
                                    logger.info("用户类型未知");
                                }
                                logger.info("解析MQ返回信息，进行判断");
                                int b = 0, l = x.length();
                                if (l > 0) {
                                    if (String.valueOf(x.charAt(0)).equals("[")) b = 1;
                                    if (String.valueOf(x.charAt(x.length() - 1)).equals("]")) l = l - 1;
                                    x = x.substring(b, l);
                                }

                                if (x.indexOf("\"result\":\"200\"") >= 0) {
                                    logger.info("扣分MQ接收成功，返回结果" + x);
                                    // 调用预占库存接口
                                    if (ifPay.equals("true")) {
                                        logger.info("打开开关，调用确认预占库存接口");
                                        // 调用7.2 确认预占库存订单接口
                                        try {
                                            Map<String, Object> queryparams = new HashMap<String, Object>();
                                            queryparams.put("jdOrderId", orderInfoDto.getJdOrderId());
                                            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                                            list = confirmOrder(queryparams);
                                            logger.info("确认预占库存订单接口返回结果》》》》》》》" + list);
                                            Map<String, Object> re = list.get(0);
                                            String resultMSg = re.get("resultMessage").toString();
                                            String resultCode = re.get("resultCode").toString();
                                            logger.info("确认接口返回信息：" + resultCode);
                                            logger.info("确认接口返回信息：" + resultMSg);
                                            if (resultCode.equals("0003")) {
                                                resultMap.put("errorCode", JDInterfaceConstant.RESULTCODE_0001);
                                                resultMap.put("resultMsg", "下单确认成功");
                                            } else {
                                                resultMap.put("errorCode", JDInterfaceConstant.RESULTCODE_3108);
                                                resultMap.put("resultMsg", "下单确认失败");
                                                // 调用事件，返还积分
                                                logger.info("下单失败，返回积分————Start");
                                                boolean isOrdered = false;
                                                boolean isReturn = false;
                                                EventShoppingJDDTO eventData = new EventShoppingJDDTO();
                                                eventData.setOrdered(isOrdered);
                                                logger.info("jd 是否下单成功——" + eventData.isOrdered());
                                                eventData.setPointNums(Long.valueOf(deductPoints));
                                                logger.info("订单需要返还的金额——" + eventData.getPointNums());
                                                eventData.setShoppingOrderNo(orderDto.getThirdOrder());
                                                logger.info("订单号——" + eventData.getShoppingOrderNo());
                                                eventData.setUserId(Integer.valueOf(userId));
                                                logger.info("下单的用户id——" + eventData.getUserId());
                                                BizEvent returnEvent = new BizEvent();
                                                returnEvent.setEventBizType(EventBizType.SHOPPIING_ORDER);
                                                returnEvent.setEventBizStep(EventBizStep.SHOPPIING_ORDER_POINTS);
                                                returnEvent.setEventKey("Return:" + eventData.getShoppingOrderNo());
                                                returnEvent.setEventData(MapConverUtil.PO2Map(eventData));
                                                String a = eventService.sendEvent2MQ(returnEvent);
                                                logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + a);
                                                int c = 0, q = a.length();
                                                if (q > 0) {
                                                    if (String.valueOf(a.charAt(0)).equals("[")) c = 1;
                                                    if (String.valueOf(a.charAt(a.length() - 1)).equals("]")) q = q - 1;
                                                    a = a.substring(c, q);
                                                }
                                                if (a.indexOf("\"result\":\"200\"") >= 0) {
                                                    logger.info("MQ接收成功，返回结果" + a);
                                                    isReturn = true;
                                                } else {
                                                    logger.info("MQ接收失败，返回结果" + a);
                                                    isReturn = false;
                                                }
                                            }
                                            logger.info("下单失败，返回积分————End");
                                        } catch (Exception e) {
                                            logger.info("Exception:", e);
                                            resultMap.put("errorCode", JDInterfaceConstant.RESULTCODE_5001);
                                            resultMap.put("errorMsg", e.getMessage());
                                        }
                                    } else {
                                        logger.info("关闭开关，不调用确认预占库存接口");
                                    }
                                } else {
                                    logger.info("MQ接收失败");
                                    resultMap.put("errorCode", JDInterfaceConstant.RESULTCODE_5001);
                                    resultMap.put("errorMsg", "扣分失败");
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.info("Exception:", e);
            resultMap.put("errorCode", JDInterfaceConstant.RESULTCODE_5001);
            resultMap.put("errorMsg", e.getMessage());
        }
        return resultMap;
    }

    /**
     * 获取一级地址
     * 
     * @param token
     */
    public void insertAddress(String token) {
        try {
            String url = "https://bizapi.jd.com/api/area/getProvince";
            String params = "token=" + token;
//            logger.info("==>params:" + params);
            String result = FrameHttpUtil.sendPost(url, params);
            logger.info("==>result:" + result);
            JSONObject data = JSONObject.fromObject(result);
            logger.info("=========>data:" + data);
            JSONObject addressResult = data.getJSONObject("result");
            logger.info("=========>data:" + addressResult);
            String key;
            TmTpAddress param = new TmTpAddress();
            param.setRankType(Short.valueOf("1"));
            tmTpAddressMapper.delete(param);
            Iterator it = addressResult.keys();
            while (it.hasNext()) {
                key = String.valueOf(it.next());
                int value = (int) addressResult.get(key);
                Long value2 = (long) value;
                TmTpAddress tmTpAddress = new TmTpAddress();
                tmTpAddress.setAddressCode(value2);
                tmTpAddress.setAddressName(key);
                tmTpAddress.setRankType((short) 1);
                tmTpAddress.setStatus((short) 0);
                tmTpAddress.setCreateDate(new Date());
                tmTpAddressMapper.insertAddress(tmTpAddress);
                logger.info("=========>tmTpAddress:" + tmTpAddress);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 保存二级地址
     * 
     * @param token
     */
    public void insertSecondAdd(String token) {
        try {
            short rankType = 1;
            String url = "https://bizapi.jd.com/api/area/getCity";
            TmTpAddress param = new TmTpAddress();
            param.setRankType(Short.valueOf("2"));
            tmTpAddressMapper.delete(param);
            List<TmTpAddress> tmTpAddressList = tmTpAddressMapper.queryAddressCode(rankType);
            for (int i = 0; i < tmTpAddressList.size(); i++) {
                Long addressCode = tmTpAddressList.get(i).getAddressCode();
                String params = "token=" + token + "&id=" + addressCode;
                String result = FrameHttpUtil.sendPost(url, params);
                logger.info("==>result:" + result);
                JSONObject data = JSONObject.fromObject(result);
                logger.info("=========>data:" + data);
                JSONObject addressResult = data.getJSONObject("result");
                logger.info("=========>data:" + addressResult);

                List<TmTpAddress> AddressList = new ArrayList<>();
                String key;
                if (!addressResult.toString().equals("null")) {
                    Iterator it = addressResult.keys();
                    while (it.hasNext()) {
                        key = String.valueOf(it.next());
                        int value = (int) addressResult.get(key);
                        Long value2 = (long) value;
                        TmTpAddress tmTpAddress = new TmTpAddress();
                        tmTpAddress.setAddressCode(value2);
                        tmTpAddress.setAddressName(key);
                        tmTpAddress.setParentCode(addressCode);
                        tmTpAddress.setRankType((short) 2);
                        tmTpAddress.setStatus((short) 0);
                        tmTpAddress.setCreateDate(new Date());
                        AddressList.add(tmTpAddress);
                        // tmTpAddressMapper.insertAddress(tmTpAddress);
                        logger.info("=========>二级地址插入集合成功:" + tmTpAddress);
                    }
                    tmTpAddressMapper.insertJDAddress(AddressList);
                    logger.info("=========>二级地址保存成功:" + tmTpAddressMapper);
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }

    }

    /**
     * 保存三级地址
     * 
     * @param token
     */
    public void insertThirdAdd(String token) {
        try {
            short rankType = 2;
            String url = "https://bizapi.jd.com/api/area/getCounty";
            TmTpAddress param = new TmTpAddress();
            param.setRankType(Short.valueOf("3"));
            tmTpAddressMapper.delete(param);
            List<TmTpAddress> tmTpAddressList = tmTpAddressMapper.queryAddressCode(rankType);
            for (int i = 0; i < tmTpAddressList.size(); i++) {
                Long addressCode = tmTpAddressList.get(i).getAddressCode();
                String params = "token=" + token + "&id=" + addressCode;
                //logger.info("==>params:" + params);
                String result = FrameHttpUtil.sendPost(url, params);
                logger.info("==>result:" + result);
                JSONObject data = JSONObject.fromObject(result);
                logger.info("=========>data:" + data);
                JSONObject addressResult = data.getJSONObject("result");
                logger.info("=========>data:" + addressResult);

                List<TmTpAddress> AddressList = new ArrayList<>();
                String key;
                if (!addressResult.toString().equals("null")) {
                    Iterator it = addressResult.keys();
                    while (it.hasNext()) {
                        key = String.valueOf(it.next());
                        int value = (int) addressResult.get(key);
                        Long value2 = (long) value;
                        TmTpAddress tmTpAddress = new TmTpAddress();
                        tmTpAddress.setAddressCode(value2);
                        tmTpAddress.setAddressName(key);
                        tmTpAddress.setParentCode(addressCode);
                        tmTpAddress.setRankType((short) 3);
                        tmTpAddress.setStatus((short) 0);
                        tmTpAddress.setCreateDate(new Date());
                        AddressList.add(tmTpAddress);

                        // tmTpAddressMapper.insertAddress(tmTpAddress);
                        logger.info("=========>三级地址插入集合成功:" + tmTpAddress);

                    }
                    tmTpAddressMapper.insertJDAddress(AddressList);
                    logger.info("=========>三级地址保存成功:" + tmTpAddressMapper);
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }

    }

    /**
     * 保存四级地址
     * 
     * @param token
     */
    public void insertFourthAdd(String token) {
        try {
            short rankType = 3;
            String url = "https://bizapi.jd.com/api/area/getTown";
            TmTpAddress param = new TmTpAddress();
            param.setRankType(Short.valueOf("4"));
            tmTpAddressMapper.delete(param);
            List<TmTpAddress> tmTpAddressList = tmTpAddressMapper.queryAddressCode(rankType);
            for (int i = 0; i < tmTpAddressList.size(); i++) {
                Long addressCode = tmTpAddressList.get(i).getAddressCode();
                String params = "token=" + token + "&id=" + addressCode;
                //logger.info("==>params:" + params);
                String result = FrameHttpUtil.sendPost(url, params);
                logger.info("==>result:" + result);
                JSONObject data = JSONObject.fromObject(result);
                logger.info("=========>data:" + data);
                JSONObject addressResult = data.getJSONObject("result");
                logger.info("=========>data:" + addressResult);

                List<TmTpAddress> AddressList = new ArrayList<>();
                String key;
                if (!addressResult.toString().equals("null")) {
                    Iterator it = addressResult.keys();
                    while (it.hasNext()) {
                        key = String.valueOf(it.next());
                        int value = (int) addressResult.get(key);
                        Long value2 = (long) value;

                        // 放入实体
                        TmTpAddress tmTpAddress = new TmTpAddress();
                        tmTpAddress.setAddressCode(value2);
                        tmTpAddress.setAddressName(key);
                        tmTpAddress.setParentCode(addressCode);
                        tmTpAddress.setRankType((short) 4);
                        tmTpAddress.setStatus((short) 0);
                        tmTpAddress.setCreateDate(new Date());

                        // 放入集合
                        AddressList.add(tmTpAddress);
                        logger.info("=========>四级地址插入集合成功:" + tmTpAddress);
                    }
                    tmTpAddressMapper.insertJDAddress(AddressList);
                    logger.info("=========>四级地址保存成功:" + tmTpAddressMapper);
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }

    }

    /**
     * 清空表数据
     */
    public void truncateAddress() {
        tmTpAddressMapper.truncateAddress();
        // tmTpAddressMapper.deleteSEQAdd();
        // tmTpAddressMapper.createSEQAdd();
    }

    public void insertTestAdd(String token) {
        try {
            short rankType = 3;
            String url = "https://bizapi.jd.com/api/area/getTown";
            List<TmTpAddress> tmTpAddressList = tmTpAddressMapper.queryAddressCode(rankType);
            for (int i = 0; i < tmTpAddressList.size(); i++) {
                Long addressCode = tmTpAddressList.get(i).getAddressCode();
                String params = "token=" + token + "&id=" + addressCode;
                logger.info("==>params:" + params);
                String result = FrameHttpUtil.sendPost(url, params);
                logger.info("==>result:" + result);
                JSONObject data = JSONObject.fromObject(result);
                logger.info("=========>data:" + data);
                JSONObject addressResult = data.getJSONObject("result");
                logger.info("=========>data:" + addressResult);

                List<TmTpAddress> AddressList = new ArrayList<>();
                String key;
                if (!addressResult.toString().equals("null")) {
                    Iterator it = addressResult.keys();
                    while (it.hasNext()) {
                        key = String.valueOf(it.next());
                        int value = (int) addressResult.get(key);
                        Long value2 = (long) value;
                        // List<TmTpAddress> addList=new
                        // ArrayList<TmTpAddress>();
                        // addList=tmTpAddressMapper.getSeq();
                        // Long seqAdd=addList.get(0).getAddressId();
                        // Long seqAdd=tmTpAddressMapper.getSeq2();

                        // 放入实体类
                        TmTpAddress tmTpAddress = new TmTpAddress();
                        // tmTpAddress.setAddressId(seqAdd);
                        tmTpAddress.setAddressCode(value2);
                        tmTpAddress.setAddressName(key);
                        tmTpAddress.setParentCode(addressCode);
                        tmTpAddress.setRankType((short) 4);
                        tmTpAddress.setStatus((short) 0);
                        tmTpAddress.setCreateDate(new Date());

                        // 放入集合
                        AddressList.add(tmTpAddress);
                    }
                    logger.info("=========>四级地址保存成功:" + tmTpAddressMapper);
                    tmTpAddressMapper.insertJDAddress(AddressList);
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }

    }

    /**
     * 校验地址
     * 
     * @param token
     * @param provinceId
     * @param cityId
     * @param countyId
     * @param townId
     * @return
     */
    public List<Map<String, Object>> checkFourAdd(String token, Long provinceId, Long cityId, Long countyId,
                                                  Long townId) {
        try {
            List<Map<String, Object>> list = new ArrayList<>();
            String url = "https://bizapi.jd.com/api/area/checkArea";
            if (countyId == null) {
                countyId = (long) 0;
            }
            if (townId == null) {
                townId = (long) 0;
            }
            String params = "token=" + token + "&provinceId=" + provinceId + "&cityId=" + cityId + "&countyId="
                            + countyId + "&townId=" + townId;
//            logger.info("==>params:" + params);
            String result = FrameHttpUtil.sendPost(url, params);
            logger.info("==>result:" + result);
            JSONObject data = JSONObject.fromObject(result);
            boolean flag = data.getBoolean("success");
            if (flag) {
                JSONObject da = JSONObject.fromObject(data.getString("result"));
                logger.info("==>da..........:" + da);
                Map<String, Object> map = new HashMap<>();
                map.put("success", da.getString("success"));
                map.put("message", da.getString("message"));
                list.add(map);
            } else {
                Map<String, Object> map = new HashMap<>();
                map.put("success", data.getString("success"));
                map.put("message", data.getString("resultMessage"));
                list.add(map);
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 取消未确认订单
     * 
     * @param jdOrderId
     * @return
     */
    public List<Map<String, Object>> cancelOrder(String jdOrderId) {
        try {
            List<Map<String, Object>> list = new ArrayList<>();
            String url = "https://bizapi.jd.com/api/order/cancel";
            String token = getToken();
            String params = "token=" + token + "&jdOrderId=" + jdOrderId;
//            logger.info("==>params:" + params);
            String result = FrameHttpUtil.sendPost(url, params);
            logger.info("==>result:" + result);
            JSONObject data = JSONObject.fromObject(result);
            boolean flag = data.getBoolean("success");
            if (flag) {
                JSONObject da = JSONObject.fromObject(data.getString("result"));
                logger.info("==>da..........:" + da);
                Map<String, Object> map = da;
                list.add(map);
            } else {
                throw new ServiceBizException(data.getString("resultMessage"));
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 商品区域购买限制查询
     * 
     * @author lyq
     * @date 2017年4月17日
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> checkAreaLimit(Map<String, Object> params) {
        try {
            List<Map<String, Object>> list = new ArrayList<>();
            String token = getToken();
            String param = "token=" + token + "&skuIds=" + params.get("skuIds") + "&province=" + params.get("province")
                           + "&city=" + params.get("city") + "&county=" + params.get("county") + "&town="
                           + params.get("town");
            String result = FrameHttpUtil.sendPost(checkAreaLimitUrl, param);
            logger.info("JDInterfaceService.checkAreaLimit==>result:" + result);
            JSONObject data = JSONObject.fromObject(result);
            boolean flag = data.getBoolean("success");
            if (flag) {
                JSONArray da = JSONArray.fromObject(data.getString("result"));
                for (int i = 0; i < da.size(); i++) {

                    Map<String, Object> map = (Map<String, Object>) da.get(i);
                    list.add(map);
                }
            } else {
                throw new ServiceBizException(data.getString("resultMessage"));
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 批量获取库存接口（建议订单详情页、下单使用）
     * 
     * @author lyq
     * @date 2017年4月17日
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> getNewStockById(Map<String, Object> params) {
        try {
            List<Map<String, Object>> list = new ArrayList<>();
            String token = getToken();
            logger.info("JDInterfaceService.getNewStockById==>token值：" + token);
            String skunums = "";
            if (!CheckUtil.NullOrEmpty(params.get("skuNums"))) {
                skunums += "[";
                List<Map<String, Object>> skus = (List<Map<String, Object>>) params.get("skuNums");
                if (skus.size() > 1) {
                    for (Map<String, Object> map : skus) {
                        skunums += "{skuId:" + map.get("skuId") + ",num:" + map.get("num") + "},";
                    }
                    skunums = skunums.substring(0, skunums.length() - 1);
                } else if (skus.size() == 1) {
                    for (Map<String, Object> map : skus) {
                        skunums += "{skuId:" + map.get("skuId") + ",num:" + map.get("num") + "}";
                    }
                }
                skunums += "]";
            }

            String param = "token=" + token + "&skuNums=" + skunums + "&area=" + params.get("area");
            String result = FrameHttpUtil.sendPost(newStockByIdUrl, param);
            logger.info("JDInterfaceService.getNewStockById==>result:" + result);
            JSONObject data = JSONObject.fromObject(result);
            boolean flag = data.getBoolean("success");
            if (flag) {
                JSONArray da = JSONArray.fromObject(data.getString("result"));
                for (int i = 0; i < da.size(); i++) {

                    Map<String, Object> map = (Map<String, Object>) da.get(i);
                    list.add(map);
                }
            } else {
                throw new ServiceBizException(data.getString("resultMessage"));
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 批量获取库存接口(建议商品列表页使用)
     * 
     * @author lyq
     * @date 2017年4月17日
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> getStockById(Map<String, Object> params) {
        try {
            List<Map<String, Object>> list = new ArrayList<>();
            String token = getToken();
            String param = "token=" + token + "&sku=" + params.get("sku") + "&area=" + params.get("area");
            String result = FrameHttpUtil.sendPost(stockByIdUrl, param);
            logger.info("JDInterfaceService.getStockById==>result:" + result);
            JSONObject data = JSONObject.fromObject(result);
            boolean flag = data.getBoolean("success");
            if (flag) {
                JSONArray da = JSONArray.fromObject(data.getString("result"));
                for (int i = 0; i < da.size(); i++) {

                    Map<String, Object> map = (Map<String, Object>) da.get(i);
                    list.add(map);
                }
            } else {
                throw new ServiceBizException(data.getString("resultMessage"));
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 7.4京东支付接口
     * 
     * @author Qiankun
     * @date 2017年4月17日
     * @return
     * @throws Exception
     */
    public Map<String, Object> doPay(String jdOrderId) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            // 查TOKEN
            String token = tpAccessTokenMapper.selectToken();
            logger.info("TOKEN——" + token);
            if (token == null || token == "") {
                // 没有获取到TOKEN
                resultMap.put("errorCode", "250");
                resultMap.put("resultMsg", "没有获取到TOKEN");
            } else {
                String url = "https://bizapi.jd.com/api/order/doPay";
                String params = "token=" + token + "&jdOrderId=" + jdOrderId;
//                logger.info("参数——" + params);
                // 发起支付
                String result = FrameHttpUtil.sendPost(url, params);
                logger.info("京东返回结果——" + result);
                // 拿到返回信息中的SUCCESS
                JSONObject jsonObject1 = JSONObject.fromObject(result);
                String success = jsonObject1.getString("success");
                if (success.equals("false")) {
                    // 支付失败
                    // 拿到错误信息中的返回码
                    String resultCode = jsonObject1.getString("resultCode");
                    String resultMessage = jsonObject1.getString("resultMessage");
                    resultMap.put("resultCode", resultCode);
                    resultMap.put("resultMessage", resultMessage);
                } else {
                    // 支付成功
                    resultMap.put("resultCode", "200");
                    resultMap.put("resultMessage", "支付成功");
                }
            }
        } catch (Exception e) {
            logger.info("Exception:", e);
            resultMap.put("errorCode", "500");
            resultMap.put("errorMsg", e.getMessage());
        }
        return resultMap;
    }

    /**
     * 确认预占库存订单接口
     * 
     * @author Administrator TODO description
     * @date 2017年5月3日
     * @param params
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> confirmOrder(Map<String, Object> params) {
        try {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            String token = getToken();
            String url = "https://bizapi.jd.com/api/order/confirmOrder";
            logger.info("JDInterfaceService.confirmOrder==>token值：" + token);
            String param = "token=" + token + "&jdOrderId=" + params.get("jdOrderId");
//            logger.info("JDInterfaceService.confirmOrder==>params:" + param);
            String result = FrameHttpUtil.sendPost(url, param);
            logger.info("JDInterfaceService.confirmOrder==>result:" + result);
            JSONObject data = JSONObject.fromObject(result);
            boolean flag = data.getBoolean("success");
            if (flag) {
                String resultMessage = data.getString("resultMessage");
                String resultCode = data.getString("resultCode");
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("resultCode", resultCode);
                map.put("resultMessage", resultMessage);
                list.add(map);
            } else {
                String resultMessage = data.getString("resultMessage");
                String resultCode = data.getString("resultCode");
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("resultCode", resultCode);
                map.put("resultMessage", resultMessage);
                list.add(map);

            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 查询京东订单信息接口
     * 
     * @author Administrator TODO description
     * @date 2017年5月9日
     * @return
     * @throws Exception
     */
    public Map<String, Object> selectJdOrder() throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String url = "https://bizapi.jd.com/api/order/selectJdOrder";
            String jdOrderId = "";
            // 获取token
            String token = getToken();
            // 查询所有已确认但是未完成的订单单号
            List<TmTpOrderInfo> resultList = tmTpOrderInfoMapper.selectJdOrder();
            if (resultList.size() == 0) {
                logger.info("暂无已确认订单");
                result.put("resultCode", JDInterfaceConstant.RESULTCODE_0000);
                result.put("resultMsg", "暂无已确认订单");
                return result;
            } else {
                for (int i = 0; i < resultList.size(); i++) {
                    jdOrderId = resultList.get(i).getJdOrderId();
                    logger.info("京东单号>>>>>>>>>>" + jdOrderId);
                    // 拼接参数
                    String param = "token=" + token + "&jdOrderId=" + jdOrderId;
                    // 调用京东接口获取京东订单信息
                    String str = FrameHttpUtil.sendPost(url, param);
                    logger.info("京东返回结果——" + str);
                    // 拿到返回信息中的SUCCESS
                    JSONObject data = JSONObject.fromObject(str);
                    String success = data.getString("success");
                    if (success.equals("true")) {
                        // 拿到物流状态
                        JSONObject da = JSONObject.fromObject(data.getString("result"));
                        String pOrder = da.getString("pOrder");
                        logger.info("父单pOrder为》》》》》" + pOrder);
                        if (pOrder.equals("0")) {
                            logger.info("处理子单");
                            for (int s = 0; s < da.size(); s++) {
                                String state = da.getString("state");
                                logger.info("拿到的物流信息>>>>>>" + state);
                                if (state.equals("1")) {
                                    logger.info("该订单已妥投>>>>>>>>" + jdOrderId);
                                    int a = updateOrderStatus(jdOrderId, JDInterfaceConstant.SEND_EXPRESS_SUCCESS);
                                    logger.info("更新数为>>>>>>>>" + a);
                                } else if (state.equals("2")) {
                                    logger.info("该订单已拒收>>>>>>>>" + jdOrderId);
                                    int a = updateOrderStatus(jdOrderId, JDInterfaceConstant.SEND_EXPRESS_FIALED);
                                    logger.info("更新数为>>>>>>>>" + a);
                                } else {
//                                    logger.info("该订单为新建订单，暂无物流信息>>>>>>>" + jdOrderId);
                                }
                            }
                        } else {
                            logger.info("处理父单");
                            JSONObject da1 = JSONObject.fromObject(data.getString("result"));
                            logger.info("拿子单信息");
                            String cOrder = da1.getString("cOrder");
                            JSONArray array = JSONArray.fromObject(cOrder);
                            logger.info("子单信息>>>>>>>" + cOrder);
                            // List<OrderDto> list = JSONArray.toList(array, OrderDto.class);
                            List<?> list2 = JSONArray.toList(array, new OrderDto(), new JsonConfig());// 参数1为要转换的JSONArray数据，参数2为要转换的目标数据，即List盛装的数据
                            for (int a = 0; a < list2.size(); a++) {
                                OrderDto person = (OrderDto) list2.get(a);
                                String state = person.getState();
                                logger.info("拿到的物流信息>>>>>>" + state);
                                if (state.equals("1")) {
                                    logger.info("该订单已妥投>>>>>>>>" + jdOrderId);
                                    int c = updateOrderStatus(jdOrderId, JDInterfaceConstant.SEND_EXPRESS_SUCCESS);
                                    logger.info("更新数为>>>>>>>>" + c);
                                } else if (state.equals("2")) {
                                    logger.info("该订单已拒收>>>>>>>>" + jdOrderId);
                                    int c = updateOrderStatus(jdOrderId, JDInterfaceConstant.SEND_EXPRESS_FIALED);
                                    logger.info("更新数为>>>>>>>>" + c);
                                } else {
                                    logger.info("该订单为新建订单，暂无物流信息>>>>>>>" + jdOrderId);
                                }
                            }
                        }
                    } else {
                        // 接口调用失败
                        result.put("resultCode", JDInterfaceConstant.RESULTCODE_5001);
                        result.put("resultMsg", "接口调用失败");
                        return result;
                    }
                }
                result.put("resultCode", JDInterfaceConstant.RESULTCODE_0000);
                result.put("resultMsg", "更新成功");
                return result;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.put("resultCode", JDInterfaceConstant.RESULTCODE_5001);
            result.put("resultMsg", "接口调用失败");
            return result;
        }
    }

    /**
     * 更新订单状态
     * 
     * @author Administrator TODO description
     * @date 2017年5月9日
     * @return
     * @throws Exception
     */
    public int updateOrderStatus(String jdOrderId, String orderStatus) throws Exception {
        int i = 0;
        TmTpOrderInfo orderInfoDto = new TmTpOrderInfo();
        try {
            orderInfoDto.setOrderStatus(orderStatus);
            logger.info("更新的状态为>>>>>>>>>" + orderInfoDto.getOrderStatus());
            Example example = new Example(TmTpOrderInfo.class);
            example.createCriteria().andCondition("JD_ORDER_ID=", jdOrderId);
            i = tmTpOrderInfoMapper.updateByExampleSelective(orderInfoDto, example);
            logger.info("更新数为>>>>>>>>" + i);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return i;
    }

    /**
     * 统一查询余额接口
     * 
     * @param token
     * @param payType
     */
    public List<Map<String, Object>> getBalance(String token, Map<String, Integer> param) {
        try {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            String url = getBalanceUrl;
            logger.info("==>getBalance.url:" + url);
            Integer payType = param.get("payType");
            String params = "token=" + token + "&payType=" + payType;
//            logger.info("==>getBalance.params:" + params);
            String result = FrameHttpUtil.sendPost(url, params);
            logger.info("==>getBalance.result:" + result);
            JSONObject data = JSONObject.fromObject(result);
            boolean flag = data.getBoolean("success");
            if (flag) {
                Double da = data.getDouble("result");
                logger.info("==>getBalance.da..........:" + da);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("result", da);
                map.put("success", data.getString("success"));
                map.put("message", data.getString("resultMessage"));
                list.add(map);
                logger.info("==>getBalance.list..........:" + list);
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                logger.info("==>getBalance.data.getString(resultMessage)..........:" + data.getString("resultMessage"));
                map.put("result", 0);
                map.put("success", data.getString("success"));
                map.put("message", data.getString("resultMessage"));
                list.add(map);
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 余额明细查询
     * 
     * @param token
     * @return
     */
    public Map<String, Object> getBalanceDetail(String token, Integer pageNum) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer total = 0;
        Integer resultPageSize = 0;
        Integer pageNo = 0;
        Integer pageCount = 0;
        Date createdDate = new Date();
        try {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            Map<String, Object> map = new HashMap<String, Object>();
            String url = getBalanceDetailUrl;
            Integer pageSize = 1000;
            logger.info("==>getBalanceDetail.url:" + url);
            String params = "token=" + token + "&pageNum=" + pageNum + "&pageSize=" + pageSize;
//            logger.info("==>getBalanceDetail.params:" + params);
            String result = FrameHttpUtil.sendPost(url, params);
            logger.info("==>getBalanceDetail.result:" + result);
            JSONObject data = JSONObject.fromObject(result);
            logger.info("==>getBalanceDetail.data:" + data);
            boolean flag = data.getBoolean("success");
            if (flag) {
                JSONObject da = data.getJSONObject("result");
                // 得到分页信息
                total = da.getInt("total");
                resultPageSize = da.getInt("pageSize");
                pageNo = da.getInt("pageNo");
                pageCount = da.getInt("pageCount");

                JSONArray resultData = da.getJSONArray("data");
                // List<TmTpBalanceDetail> ppList = JSONArray.toList(resultData, new TmTpBalanceDetail(), new
                // JsonConfig());
                // 循环
                // for(TmTpBalanceDetail pp : ppList) {
                for (int i = 0; i < resultData.size(); i++) {
                    Integer ifExist = tmTpBalanceDetailMapper.selectIfExist(resultData.getJSONObject(i).getLong("id"));
                    if (ifExist == 0 || ifExist == null) {
                        TmTpBalanceDetail tmTpBalanceDetail = new TmTpBalanceDetail();
                        tmTpBalanceDetail.setId(resultData.getJSONObject(i).getLong("id"));
                        tmTpBalanceDetail.setAccountType(resultData.getJSONObject(i).getLong("accountType"));
                        tmTpBalanceDetail.setAmount(resultData.getJSONObject(i).getLong("amount"));
                        tmTpBalanceDetail.setPin(resultData.getJSONObject(i).getString("pin"));
                        tmTpBalanceDetail.setOrderId(resultData.getJSONObject(i).getString("orderId"));
                        tmTpBalanceDetail.setTradeType(resultData.getJSONObject(i).getLong("tradeType"));
                        tmTpBalanceDetail.setTradeTypeName(resultData.getJSONObject(i).getString("tradeTypeName"));
                        tmTpBalanceDetail.setCreatedDate(sdf.parse(resultData.getJSONObject(i).getString("createdDate")));
                        tmTpBalanceDetail.setNotePub(resultData.getJSONObject(i).getString("notePub"));
                        tmTpBalanceDetail.setTradeNo(resultData.getJSONObject(i).getLong("tradeNo"));
                        tmTpBalanceDetail.setCreateDate(new Date());
                        tmTpBalanceDetail.setCreateBy(Long.valueOf(JDInterfaceConstant.WX_USER_ID));
                        tmTpBalanceDetailMapper.insertSelective(tmTpBalanceDetail);
                        logger.info("==>getBalanceDetail.insertBalanceDetail:余额明细表中不存在该条数据，插入数据成功:"
                                    + tmTpBalanceDetail.getId());
                    } else {
                        logger.info("==>getBalanceDetail.insertBalanceDetail:余额明细表中存在该条数据:不插入该条数据:"
                                    + resultData.getJSONObject(i).getLong("id"));
                    }

                }
                // 判断是否存在该条数据
                /*
                 * Integer ifExist=tmTpBalanceDetailMapper.selectIfExist(pp.getId());
                 * logger.info("==>getBalanceDetail.selectIfExist:" + ifExist); if(ifExist==0||ifExist==null){
                 * createdDate=pp.getCreatedDate(); logger.info("==>时间:CreatedDate。。。。。。。。。。。。。。。" + createdDate);
                 * pp.setCreateDate(new Date()); pp.setCreateBy(Long.valueOf(JDInterfaceConstant.WX_USER_ID));
                 * tmTpBalanceDetailMapper.insertSelective(pp);
                 * logger.info("==>getBalanceDetail.insertBalanceDetail:余额明细表中不存在该条数据，插入数据成功:" + pp.getId()); }else{
                 * logger.info("==>getBalanceDetail.insertBalanceDetail:余额明细表中存在该条数据:不插入该条数据" + pp.getId()); } }
                 */
                map.put("total", total);
                map.put("pageSize", resultPageSize);
                map.put("pageNo", pageNo);
                map.put("pageCount", pageCount);
                logger.info("==>getBalanceDetail.map..........:" + map);
            } else {
                logger.info("==>getBalanceDetail.data.getString(resultMessage)..........:"
                            + data.getString("resultMessage"));
                throw new ServiceBizException(data.getString("resultMessage"));
            }
            return map;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 获取余额明细分页
     * 
     * @param token
     */
    public void pageBalanceDetail(String token) {
        Integer pageNum = 1;
        Map<String, Object> map = new HashMap<String, Object>();
        map = getBalanceDetail(token, pageNum);
        Integer pageCount = (Integer) map.get("pageCount");
        if (pageCount > 1) {
            for (int i = 2; i <= pageCount; i++) {
                getBalanceDetail(token, i);
            }
        }
    }

    /**
     * 查询用户金彩余额
     * 
     * @param token
     */
    public Map<String, Object> selectJincaiCredit(String token) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            String url = selectJincaiCreditUrl;
            logger.info("==>selectJincaiCredit.url:" + url);
            String params = "token=" + token;
//            logger.info("==>selectJincaiCredit.params:" + params);
            String result = FrameHttpUtil.sendPost(url, params);
            logger.info("==>selectJincaiCredit.result:" + result);
            JSONObject data = JSONObject.fromObject(result);
            boolean flag = data.getBoolean("success");
            if (flag) {
                JSONObject da = data.getJSONObject("result");
                logger.info("==>selectJincaiCredit.da..........:" + da);
                map.put("result", da);
                // 目前还没开通金彩支付
                // map.put("creditLimit",da.getDouble("creditLimit"));//授信额度
                // map.put("remainLimit",da.getDouble("remainLimit"));//可用额度
                // map.put("debtSumAmt",da.getDouble("debtSumAmt"));//代还款总额
                // map.put("penaltySumAmt",da.getDouble("penaltySumAmt"));//违约金总额
                map.put("success", data.getString("success"));
                map.put("message", data.getString("resultMessage"));
                logger.info("==>selectJincaiCredit.map..........:" + map);
            } else {
                logger.info("==>selectJincaiCredit.data.getString(resultMessage)..........:"
                            + data.getString("resultMessage"));
                map.put("result", null);
                map.put("success", data.getString("success"));
                map.put("message", data.getString("resultMessage"));
                logger.info("==>selectJincaiCredit.map..........:" + map);
            }
            return map;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    public String shoppingSendMq(String openId, Long deductPoints) throws Exception {
        String s = "";
        try {
            logger.info("MaintainSend——Start");
            SendMessage<List<EventShoppingSendWeixinDto>> l = new SendMessage<List<EventShoppingSendWeixinDto>>();
            List<EventShoppingSendWeixinDto> list = new ArrayList<EventShoppingSendWeixinDto>();
            EventShoppingSendWeixinDto dto = new EventShoppingSendWeixinDto();
            dto.setOpenID(openId);
            logger.info("参数OPEN_ID>>>>>>>>>>>>" + dto.getOpenID());
            dto.setPoints(deductPoints);
            logger.info("参数deductPoints>>>>>>>>>>>>" + dto.getPoints());
            list.add(dto);
            logger.info("dto添加入list中");
            l.setIfcode("IC022");
            l.setIfdata(list);
            logger.info("list拼到IfData中");
            String data = JSON.toJSONString(l).toString();
            logger.info("推送到MQ的数据为>>>>>" + data);
            s = eventService.sendMessage2MQ(MQChannelType.appShoppingPoints, data);
            logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
            logger.info("SendEnd");
            return s;
        } catch (Exception e) {
            logger.info("调用MQ异常：" + e.getMessage());
            throw e;
        }
    }
}
